package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.budwk.app.sqfw.dto.PeopleTagDTO;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.DownDataVo;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.baiyunqu.OldPeopleSeekPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.weiqingmen.HouseHoldSurveyDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.InterviewDTO;
import com.budwk.app.sqfwV2.enums.OldPeopleSeekEnum;
import com.budwk.app.sqfwV2.service.baiyunqu.OldPeopleSeekExcelService;
import com.budwk.app.sqfwV2.service.baiyunqu.OldPeopleSeekPdfService;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.openapi.annotation.ApiResponses;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 特殊老年人探访
 * @BelongsProject: dfxy-shequ
 * @Author: yangweimin
 * @CreateTime: 2024-03-12  11:16
 * @Description: TODO
 */
@IocBean
@At("/platform/sqfw/baiYunQuOldPeopleSeek")
@ApiDefinition(tag = "特殊老年人探访")
@Slf4j
public class BaiYunQuOldPeopleSeekController {
    @Inject
    private OldPeopleSeekPdfService oldPeopleSeekPdfService;
    @Inject
    private OldPeopleSeekExcelService oldPeopleSeekExcelService;
    @Inject
    private PersonInfoService personInfoService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @At("/v2/submitData")
    @Ok("json")
    @POST
    @ApiOperation(name = "保存数据并创建pdf")
    @SLog(tag = "保存数据并创建pdf", value = "${args[0]}")
    public Result<?> submitData(@Param("..") TemplateCodeUpdateDTO dto) {
        oldPeopleSeekPdfService.submitData(dto);
        return Result.success();
    }

    @At("/v2/list")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取列表数据 2.0版本")
    @ApiResponses
    @SaCheckLogin
    public Result<?> list(@Param("pageNo") Integer pageNo, @Param("pageSize") Integer pageSize,
                          @Param("sort") String sort, @Param("fillDate") String fillDate,
                          @Param("id") String id, @Param("category") String category) {
        return oldPeopleSeekPdfService.list(pageNo, pageSize, fillDate, sort, id, category);
    }

    @At("/v2/update")
    @Ok("json")
    @POST
    @ApiOperation(name = "更新 2.0版本")
    @SaCheckLogin
    public Result<?> update(@Param("..") TemplateCodeUpdateDTO dto) {
        oldPeopleSeekPdfService.update(dto);
        return Result.success();
    }

    @At("/v2/latest")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取探访人最新一条探访记录 2.0版本")
    @SaCheckLogin
    public Result<?> getLatest(@Param("personInfoId") String personInfoId) {
        return Result.data(oldPeopleSeekPdfService.getLatest(personInfoId));
    }

    @At("/v2/checkData")
    @Ok("json")
    @POST
    @ApiOperation(name = "数据检测 2.0版本")
    @SaCheckLogin
    public Result<?> checkData(@Param("..") DownExcelLedgerReqVo reqVo) {

        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();

        reqVo.setCheckData(true);

        // pdf
        List<ResultOfExcelGenerator> generatePdfUrlVOList = oldPeopleSeekPdfService.downPdfList(reqVo);
        for (ResultOfExcelGenerator vo : generatePdfUrlVOList) {
            OldPeopleSeekEnum pdf = OldPeopleSeekEnum.getEnum(vo.getFileIdentity());
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(pdf.getName())
                    .setPreviewImage(List.of(pdf.getImg().split(",")))
                    .setFileCode(String.valueOf(pdf.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(Integer.parseInt(pdf.getCode()))
                    .setFileName(pdf.getCompilationName())
                    .setFileType(pdf.getFileType())
                    .setHiveData(vo.getPassCreateConditionFlag() == null ? false : vo.getPassCreateConditionFlag());
            downFileTypesResVos.add(resVo);
        }

        // excel
        DownDataVo<ResultOfExcelGenerator> downDataVo = oldPeopleSeekExcelService.createExcel(reqVo);
        List<ResultOfExcelGenerator> generateExcelUrlVOList = downDataVo.getVoList();
        for (ResultOfExcelGenerator vo : generateExcelUrlVOList) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            OldPeopleSeekEnum excel = OldPeopleSeekEnum.getEnum(vo.getFileIdentity());
            resVo.setLabel(excel.getName())
                    .setPreviewImage(List.of(excel.getImg().split(",")))
                    .setFileCode(String.valueOf(excel.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(Integer.parseInt(excel.getCode()))
                    .setFileName(excel.getCompilationName())
                    .setFileType(excel.getFileType())
                    .setHiveData(vo.getPassCreateConditionFlag() == null ? false : vo.getPassCreateConditionFlag());
            downFileTypesResVos.add(resVo);
        }
        return Result.data(NutMap.NEW().addv("list", downFileTypesResVos).addv("totalCount", downDataVo.getTotalCount()));
    }

    @At("/v2/downPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载pdf 2.0版本")
    @SaCheckLogin
    public Result<?> downPdf(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<ResultOfExcelGenerator> generatePdfUrlVOList = oldPeopleSeekPdfService.downPdfList(reqVo);
        return Result.data(generatePdfUrlVOList);
    }

    @At("/v2/downExcel")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载excel 2.0版本")
    @SaCheckLogin
    public Result<?> downExcel(@Param("..") DownExcelLedgerReqVo reqVo) {
        DownDataVo<ResultOfExcelGenerator> downDataVo = oldPeopleSeekExcelService.createExcel(reqVo);
        return Result.data(downDataVo.getVoList());
    }

    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "新增人员信息")
    @SaCheckLogin
    public Result<?> addPersonInfo(@Param("..") PersonInfo personInfo) {
        return oldPeopleSeekPdfService.addPersonInfo(personInfo);
    }

    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "更新人员信息")
    @SaCheckLogin
    public Result<?> updatePersonInfo(@Param("..") PersonInfo personInfo) {
        return oldPeopleSeekPdfService.updatePersonInfo(personInfo);
    }

    @At()
    @Ok("json")
    @GET
    @ApiOperation(name = "获取人员信息")
    @SaCheckLogin
    public Result<?> getPersonInfo(@Param("id") String id) {
        return Result.data(personInfoService.fetch(id));
    }


    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "获取人员信息列表")
    @SaCheckLogin
    public Result<?> listPage(@Param("pageNo") Integer pageNo, @Param("pageSize") Integer pageSize,
                              @Param("query") String query, @Param("category") String category) {
        return Result.data(oldPeopleSeekPdfService.pagePersonInfo(pageNo, pageSize, query, category));
    }
    

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "创建pdf")
    @ApiResponses
    @SLog(tag = "创建pdf", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> createPdf(@Param("..") TemplateCodeUpdateDTO templateCodeUpdateDTO) {
        log.info("特殊老年人探访：{}", JSONUtil.toJsonStr(templateCodeUpdateDTO));
        oldPeopleSeekPdfService.createPdfAndMsg(templateCodeUpdateDTO);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载excel（数据检测、模板下载、数据下载都用此接口）")
    @SLog(tag = "下载excel", value = "${args[0]}")
    public Result<?> downExcel(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList,
                               @Param("sqfwIdList") List<String> sqfwIdList) {
        List<ResultOfExcelGenerator> excelList = oldPeopleSeekExcelService.createExcel(excelConfigList, sqfwIdList);
        return Result.success(excelList);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取单位所有excel（数据检测、模板下载、数据下载都用此接口）")
    @SLog(tag = "获取单位所有excel", value = "${args[0]}")
    public Result<?> createExcelToUnit(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList) {
        List<ResultOfExcelGenerator> excelList = oldPeopleSeekExcelService.createExcelToUnit(excelConfigList);
        return Result.success(excelList);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "pdf合集下载")
    @ApiResponses
    @SLog(tag = "pdf合集下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downPdfList(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList,
                                 @Param("sqfwIdList") List<String> sqfwIdList) {
        return Result.success(oldPeopleSeekPdfService.downPdfList(excelConfigList, sqfwIdList));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取单位下所有pdf数据")
    @ApiResponses
    @SLog(tag = "获取单位下所有pdf数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downPdfListToUnit(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList) {
        return Result.success(oldPeopleSeekPdfService.downPdfListToUnit(excelConfigList));
    }

    /**
     * 获取回显列表
     * @param name
     * @return
     */
    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "获取回显列表")
    @ApiResponses
    @SLog(tag = "获取回显列表", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> echo(@Param("name") String name) {
        return Result.success(oldPeopleSeekPdfService.echo(name));
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> get(@Param("id") String id) {
        return Result.success(oldPeopleSeekPdfService.get(id));
    }


    @At()
    @Ok("json")
    @GET
    @ApiOperation(name = "数据清洗")
    //@SaCheckLogin
    public Result<?> dataCleanse() {
        dataCleanse(0);
        return Result.success();
    }

    private void dataCleanse(int page) {
        String sql = "select * from shequ.sqfw_form_summary_new where type='"+oldPeopleSeekPdfService.getSummaryType()+"' order by create_date asc LIMIT 100 OFFSET " + page;
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.listEntity(Sqls.create(sql));
        for (Sqfw_formSummary_new formSummary : formSummaryList) {
            System.out.println("老数据："+ JSON.toJSONString(formSummary));
            try {
                if (StringUtils.isNotBlank(formSummary.getParamData())) {
                    // 添加人员
                    OldPeopleSeekPdfDTO pdfDTO = JSONUtil.toBean(formSummary.getParamData(), OldPeopleSeekPdfDTO.class);
                    PersonInfo personInfo;

                    Cnd cnd = Cnd.NEW();
                    cnd.and(PersonInfo::getName, "=", pdfDTO.getNameOfTheInterviewee());
                    cnd.and(PersonInfo::getProvince, "=", formSummary.getProvince());
                    cnd.and(PersonInfo::getCity, "=", formSummary.getCity());
                    cnd.and(PersonInfo::getDistrict, "=", formSummary.getDistrict());
                    cnd.and(PersonInfo::getCounty, "=", formSummary.getCounty());
                    cnd.and(PersonInfo::getCommunity, "=", formSummary.getCommunity());
                    personInfo = personInfoService.fetch(cnd);
                    if (personInfo == null) {
                        personInfo = new PersonInfo();

                        personInfo.setName(pdfDTO.getNameOfTheInterviewee());
                        personInfo.setPhone(pdfDTO.getOperatorTelephone());
                        personInfo.setUnitName(formSummary.getUnitName());
                        personInfo.setProvince(formSummary.getProvince());
                        personInfo.setCity(formSummary.getCity());
                        personInfo.setDistrict(formSummary.getDistrict());
                        personInfo.setCounty(formSummary.getCounty());
                        personInfo.setCommunity(formSummary.getCommunity());
                        personInfo.setCreateBy(formSummary.getCreateBy());
                        personInfo.setUpdateBy(formSummary.getUpdateBy());
                        personInfo.setCreateDate(LocalDateTime.now());
                        personInfo.setAddress(pdfDTO.getAddress());
                        personInfo.setBusinessType(oldPeopleSeekPdfService.getSummaryType());

                        personInfo = personInfoService.insert(personInfo);
                    } else {
                        personInfo.setName(pdfDTO.getNameOfTheInterviewee());
                        if (StringUtils.isNotBlank(pdfDTO.getOperatorTelephone())) {
                            personInfo.setPhone(pdfDTO.getOperatorTelephone());
                        }
                        personInfo.setUnitName(formSummary.getUnitName());
                        personInfo.setProvince(formSummary.getProvince());
                        personInfo.setCity(formSummary.getCity());
                        personInfo.setDistrict(formSummary.getDistrict());
                        personInfo.setCounty(formSummary.getCounty());
                        personInfo.setCommunity(formSummary.getCommunity());
                        personInfo.setCreateBy(formSummary.getCreateBy());
                        personInfo.setUpdateBy(formSummary.getUpdateBy());
                        personInfo.setCreateDate(LocalDateTime.now());
                        if (StringUtils.isNotBlank(pdfDTO.getAddress())) {
                            personInfo.setAddress(pdfDTO.getAddress());
                        }
                        String type = personInfo.getBusinessType()+","+oldPeopleSeekPdfService.getSummaryType();
                        personInfo.setBusinessType(type);
                        personInfoService.updateIgnoreNull(personInfo);
                    }

                    // 更新巡查
                    pdfDTO.setId(personInfo.getId());
                    formSummary.setParamData(JSONUtil.toJsonStr(pdfDTO));
                    sqfwFormsummaryNewService.updateIgnoreNull(formSummary);
                    //oldPeopleSeekPdfService.reCreatePdfAndMsg(formSummary.getSqfwFlowId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (formSummaryList.size() == 100) {
            page += 100;
            dataCleanse(page);
        }
    }
}
